<template>
	<view class="container">
		<uni-forms ref="stockForm" :modelValue="info"  :rules="stockRules" class="form" label-width="120">			
			<uni-forms-item label="资产分类" class="form-item">
				<view class="uni-input">{{info.cateName}}</view>
			</uni-forms-item>
			<uni-forms-item label="资产编码" class="form-item">
				<view class="uni-input">{{info.assetNum}}</view>
			</uni-forms-item>
			<uni-forms-item label="所属部门" class="form-item">
				<view class="uni-input">{{info.deptName}}</view>
			</uni-forms-item>
			<template  v-if="info.id">				
			<uni-forms-item label="资产图例" class="form-item">
				<view class="uni-input" @click="previewImgs" v-if="imageList">
					<image style="height: 200px; background-color: #eeeeee;" 
					mode="aspectFit" :src="imageList[0]"></image>
				</view>
				<view class="uni-input" v-else @click="previewImgs">点击上传</view>
			</uni-forms-item>
			<uni-forms-item label="原价值" class="form-item">
				<view class="uni-input">{{info.priceOld}}</view>
			</uni-forms-item>
			<uni-forms-item label="当前价值" class="form-item">
				<view class="uni-input" v-if="action == 'view'">{{info.priceNew}}</view>
				<uni-easyinput v-else v-model="info.priceNew" placeholder="请输入当前价值" />
			</uni-forms-item>
			<uni-forms-item label="是否在库" class="form-item" required>
				<view class="uni-input" v-if="action == 'view'">{{dictTag('sys_yes_no', info.inStore)}}</view>
				<view v-else>
					<switch :checked="info.inStore == 'Y'" @change="switchInStoreChange" />
				</view>
			</uni-forms-item>
			<uni-forms-item label="所在仓库" class="form-item" v-if="info.inStore == 'Y'">
				<view class="uni-input" v-if="action == 'view'">{{info.houseName}}</view>
				<picker v-else @change="bindHouseChange" :value="houseIndex" :range="houseOptions">
					<view class="uni-input">{{houseName}}</view>
				</picker>
			</uni-forms-item>
			<uni-forms-item label="是否在用" class="form-item" required>
				<view class="uni-input" v-if="action == 'view'">{{dictTag('sys_yes_no', info.isUse)}}</view>
				<view v-else>
					<switch :checked="info.isUse == 'Y'" @change="switchIsUseChange" />
				</view>
			</uni-forms-item>
			<uni-forms-item label="当前使用人" class="form-item" v-if="info.isUse == 'Y'">
				<view class="uni-input" v-if="action == 'view'">{{info.userName}}</view>
				<picker v-else @change="bindUserChange" :value="userIndex" :range="userOptions">
					<view class="uni-input">{{userName}}</view>
				</picker>
			</uni-forms-item>
			<uni-forms-item label="当前状态" class="form-item" required>
				<view class="uni-input" v-if="action == 'view'">{{dictTag('asset_status', info.status)}}</view>
				<picker v-else @change="bindStatusChange" :value="statusIndex" :range="statusOptions">
					<view class="uni-input">{{assetStatus}}</view>
				</picker>
			</uni-forms-item>
			</template>
		</uni-forms>
		<button type="primary" v-if="action == 'stock'" @click="handleSubmit('stockForm')">保存盘点信息</button>	
	</view>
</template>


<script>
	import { getStockDetail, updateStockDetail} from '@/api/stock.js'
	import { selectWarehouse } from "@/api/base.js";
	import { queryDs } from '@/api/dataset.js'
	import upload from '@/utils/upload.js'	
	import config from '@/config'
	const baseUrl = config.baseUrl
	import { dictMixin } from '@/plugins/dict.js';
	export default {
		mixins: [dictMixin],
		data() {
			return {
				info: { },
				action: 'view',
				actionItems: [],
				houseIndex: 0,
				houseList: [],
				houseOptions: [],
				yesNoOptions: [],
				statusOptions: [],
				statusIndex: 0,
				userOptions: [],
				userList: [],
				userIndex: 0,				
				imgItems: ['预览', '重新拍照'],
				imageLimit: 3,
				// 校验规则
				stockRules: {
					inStore: {
						rules: [{
							required: true,
							errorMessage: '是否在库不能为空'
						}]
					},
					isUse: {
						rules: [{
							required: true,
							errorMessage: '是否在用不能为空'
						}]
					},
					status: {
						rules: [{
							required: true,
							errorMessage: '资产状态不能为空'
						}]
					}
				}
			}
		},
		onLoad() {
			this.useDict(['asset_status', 'sys_yes_no'], ()=>{		
				this.statusOptions = ['未选择'];
				this.dictOptions['asset_status'].forEach(dd=>{
					this.statusOptions.push(dd.dictLabel);
				})
				
				this.yesNoOptions = [];
				this.dictOptions['sys_yes_no'].forEach(dd=>{
					this.yesNoOptions.push(dd.dictLabel);
				})
				
				this.initPicker();
			});
			
			getStockDetail(this.$route.query.id).then(response => {
				this.info = response.data;				
			})
			
			if(this.$route.query.action){
				this.action = this.$route.query.action;
				if(this.action != 'view'){
					this.loadDs();
				}
			}						
		},
		onReady() {
			this.$refs.stockForm.setRules(this.stockRules)			
		},
		computed: {
			imageList() {
				if(!this.info.imgs){
					return null;
				}else { 
					return this.info.imgs.split(',').map(e=>baseUrl+e);
				}
			},
			houseName() {
				if(!this.info.houseId || this.houseIndex == 0){
					return '未选择';
				}else if(this.houseList.length == 0){
					return '';
				}else { 
					return this.houseList[this.houseIndex-1].name;
				}
			},
			userName() {
				if(!this.info.userId  || this.userIndex == 0){
					return '未选择';
				} else if(this.userList.length == 0){
					return '';
				}else { 
					return this.userList[this.userIndex-1].label;
				}
			},
			assetStatus() {
				if(!this.info.status  || this.statusIndex == 0){
					return '未选择';
				}else if(this.dictOptions['asset_status'].length == 0){
					return '';
				}else { 
					return this.dictOptions['asset_status'][this.statusIndex-1].dictLabel;
				}
			}
		},
		methods: {
			loadDs() {
				this.houseOptions = ['未选择'];
				selectWarehouse({status:'1'}).then(response=>{
					this.houseList = response.data;
					response.data.forEach(h=>{
						this.houseOptions.push(h.name);
					})
					this.initPicker();
				})
				
				this.userOptions = ['未选择'];
				queryDs({code:'sys_user_select'}).then(response=>{
					this.userList = response.data;
					response.data.forEach(u=>{
						this.userOptions.push(u.label);
					})
					this.initPicker();
				});				
				
			},
			initPicker() {
				if(this.info.id == null || this.action == 'view'){
					return;
				}
				if(this.houseList.length > 0 && this.info.houseId){
					for(let i=0;i<this.houseList.length;i++){
						if(this.houseList[i].id == this.info.houseId){
							this.houseIndex = i+1;
							break;
						}
					}
				}
				if(this.userList.length > 0 && this.info.userId){
					for(let i=0;i<this.userList.length;i++){
						if(this.userList[i].value == this.info.userId){
							this.userIndex = i+1;
							break;
						}
					}
				}
				if(this.dictOptions['asset_status'] != null && this.dictOptions['asset_status'].length > 0 && this.info.status != null){
					for(let i=0;i<this.dictOptions['asset_status'].length;i++){
						if(this.dictOptions['asset_status'][i].dictValue == this.info.status){
							this.statusIndex = i+1;
							break;
						}
					}
				}
			},
			switchInStoreChange(e) {
				this.info.inStore = e.detail.value ? 'Y':'N';
			},
			switchIsUseChange(e) {
				this.info.isUse = e.detail.value ? 'Y':'N';
			},
			bindHouseChange(e) {
				if(e.detail.value == 0){
					return;
				}
				this.houseIndex = e.detail.value;
				this.info.houseId = this.houseList[e.detail.value-1].id;
			},
			bindUserChange(e) {
				if(e.detail.value == 0){
					return;
				}
				this.userIndex = e.detail.value;
				this.info.userId = this.userList[e.detail.value-1].value;
			},
			bindStatusChange(e) {
				if(e.detail.value == 0){
					return;
				}
				this.statusIndex = e.detail.value;
				this.info.status = this.dictOptions['asset_status'][e.detail.value-1].dictValue;
			},
			previewImgs() {
				if(this.imageList == null || this.imageList.length == 0){
					this.uploadImgs();
					return;
				}
				let that = this;
				uni.showActionSheet({
					itemList: this.imgItems,
					success: function (res) {
						if(res.tapIndex == 0){
							//预览
							uni.previewImage({
								current: 0,
								urls: that.imageList
							});
						}else{
							//上传
							that.uploadImgs();
						}
					},
					fail: function (res) {
						console.log(res.errMsg);
					}
				});
				
			},
			handleSubmit(ref) {
				let that = this;
				this.$refs[ref].validate().then(res => {
					updateStockDetail(this.info).then(response => {
						that.$modal.msgSuccess('保存成功');
						//this.$tab.navigateBack();						
					});
				})
			},
			uploadImgs() {
				let imgFiles = [];
				let that = this;
				uni.chooseImage({
					count: this.imageLimit, //默认9
					sizeType: ['compressed'], //可以指定是原图还是压缩图，默认二者都有
					//sourceType: ['album'], //从相册选择
					success: function (res) {
						res.tempFilePaths.forEach(temp=>{
							upload({
							  url: '/common/upload',
							  name: "file",
							  filePath: temp
							}).then(response=>{
								imgFiles.push(response.fileName)
								that.info.imgs = imgFiles.join(',')
							})
						})
					}
				});
			}
		}
	}
</script>

<style>
	.form {
		padding: 15px;
		background-color: #fff;
	}
	.button-group {
		margin-top: 15px;
		display: flex;
		justify-content: space-around;
	}

	.form-item {
		display: flex;
		align-items: center;
		place-items: center;
	}

	.button {
		display: flex;
		align-items: center;
		height: 35px;
		margin-left: 10px;
	}
</style>